/****************************************************************************
 *
 * Copyright (C) 2003-2010 Los Alamos National Security, LLC
 *                         Packet Analytics Corporation
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License Version 2 as
 * published by the Free Software Foundation.  You may not use, modify or
 * distribute this program under any other version of the GNU General
 * Public License.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 *
 ****************************************************************************/
package nfse.dataset.apache;

import java.sql.Timestamp;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.StringTokenizer;
import java.util.TimeZone;

import nfse.NetFSE;
import nfse.NetFSERecord;
import nfse.NetFSEUtil;
import nfse.gui.server.GUIRecordFactory;
import nfse.gui.server.RecordBuilderUtil;

public class Apache2AccessRecordFactory extends GUIRecordFactory<Apache2AccessRecord> {

    public Apache2AccessRecordFactory() {
        builder = new RecordBuilderUtil();
        builder.addColumn(null,"ID", RecordBuilderUtil.BIGINT);
        builder.addColumn("Start TS","startts", RecordBuilderUtil.TIMESTAMP);
        builder.addColumn("Src IP","srcip", RecordBuilderUtil.INET);
        builder.addColumn("Dst IP","dstip", RecordBuilderUtil.INET);
        builder.addColumn("User Name","username", RecordBuilderUtil.VARCHAR,500);
        builder.addColumn("User Agent","useragent", RecordBuilderUtil.VARCHAR,500);
        builder.addColumn("Request","getrequest", RecordBuilderUtil.VARCHAR,500);
        builder.addColumn("URL","url", RecordBuilderUtil.VARCHAR,500);
        builder.addColumn("HTTP Code","httpcode", RecordBuilderUtil.INTEGER);
        builder.addColumn("Bytes","bytes", RecordBuilderUtil.BIGINT);
    }
    
    @Override
    protected void setValues(Apache2AccessRecord record, int id) {
        int idx = -1;
        builder.setFieldValue(++idx, "" + id);
        builder.setFieldValue(++idx, "" + record.getStartTS());
        builder.setFieldValue(++idx, record.getSrcAddr());
        builder.setFieldValue(++idx, record.dstAddr);
        builder.setFieldValue(++idx, "" + record.userName);
        builder.setFieldValue(++idx, "" + record.userAgent);
        builder.setFieldValue(++idx, record.url);
        builder.setFieldValue(++idx, "" + record.getRequest);
        builder.setFieldValue(++idx, "" + record.httpCode);
        builder.setFieldValue(++idx, "" + record.bytes);
    }
    
    @Override
    public NetFSERecord generate(String line, int sensor) {
        try {

            // 192.168.0.50 - ben [23/Jan/2008:14:58:21 -0700] "GET /trac
            // HTTP/1.1" 200
            // 6415 "-" "Mozilla/5.0 (Macintosh; U; Intel Mac OS X; en)
            // AppleWebKit/523.12.2 (KHTML, like Gecko) Version/3.0.4
            // Safari/523.12.2"

            Apache2AccessRecord rec = new Apache2AccessRecord(sensor);

            rec.setSensorID(sensor);

            int idx1 = line.indexOf(";");
            int idx2 = line.indexOf(";", idx1 + 2);
            int colIdx = line.indexOf(":", idx2 + 15);

            String dstIP = line.substring(idx1 + 1, idx2);
            if (!dstIP.equals("-1")) {
                rec.setDstIP(NetFSEUtil.convertIPtoLong(dstIP));
            }

            String tsStr = line.substring(0, idx1);
            if (!tsStr.equals("-1")) {
                java.sql.Timestamp ts = new java.sql.Timestamp(Long.parseLong(tsStr) * 1000);
                rec.setStartTS(ts);
            } else {
                tsStr = line.substring(idx2, colIdx);
                java.sql.Timestamp ts = NetFSEUtil.timestampFromSyslog(tsStr);
                rec.setStartTS(ts);
                line = ts.getTime() / 1000 + line.substring(idx1);
                idx1 = line.indexOf(";");
                idx2 = line.indexOf(";", idx1 + 2);
                colIdx = line.indexOf(":", idx2 + 15);
            }

            StringTokenizer st = new StringTokenizer(line.substring(colIdx + 1).trim(), "\"");

            String token1 = st.nextToken();

            String[] headerTokens = token1.trim().split(" +");
            rec.setSrcIP(NetFSEUtil.convertIPtoLong(headerTokens[0]));
            rec.userName = headerTokens[2];

            headerTokens[3] = headerTokens[3].substring(1);
            int tsColIdx = headerTokens[3].indexOf(":");
            String[] dtTokens = headerTokens[3].substring(0, tsColIdx).split("/");
            String[] timeTokens = headerTokens[3].substring(tsColIdx + 1).split(":");
            GregorianCalendar cal = new GregorianCalendar();
            cal.set(Calendar.MILLISECOND, 0);
            cal.set(Calendar.DAY_OF_MONTH, Integer.parseInt(dtTokens[0]));
            cal.set(Calendar.MONTH, NetFSE.getMonthValue(dtTokens[1]));
            cal.set(Calendar.YEAR, Integer.parseInt(dtTokens[2]));
            cal.set(Calendar.HOUR_OF_DAY, Integer.parseInt(timeTokens[0]));
            cal.set(Calendar.MINUTE, NetFSE.getMonthValue(timeTokens[1]));
            cal.set(Calendar.SECOND, Integer.parseInt(timeTokens[2]));

            TimeZone tz = TimeZone.getTimeZone("GMT" + headerTokens[4]);
            cal.setTimeZone(tz);

            rec.setStartTS(new Timestamp(cal.getTimeInMillis()));

            rec.getRequest = st.nextToken();

            String token2 = st.nextToken().trim();
            int idx = token2.indexOf(" ");

            rec.httpCode = Integer.parseInt(token2.substring(0, idx));
            rec.bytes = Integer.parseInt(token2.substring(idx + 1));
            rec.url = st.nextToken();

            String token4 = st.nextToken(); // White space
            rec.userAgent = st.nextToken().trim();

            rec.setInitialString(line);

            
            return rec;
        } catch (Exception E) {
            E.printStackTrace();
        }
        return null;
    }

    @Override
    public NetFSERecord generate() {
        return new Apache2AccessRecord();
    }

    



}
